package io.github.mosiki.modules.sys.service.impl;

import io.github.mosiki.modules.sys.converter.SysRoleConverter;
import io.github.mosiki.modules.sys.domain.SysRole;
import io.github.mosiki.modules.sys.dto.SysRoleDTO;
import io.github.mosiki.modules.sys.repository.SysRoleRepository;
import io.github.mosiki.modules.sys.service.SysRoleMenuService;
import io.github.mosiki.modules.sys.service.SysRoleService;
import io.github.mosiki.modules.sys.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service("SysRoleService")
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleRepository sysRoleRepository;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public Page<SysRoleDTO> listRole(Map<String, Object> params, PageRequest pageRequest) {
        //TODO 参数没用上 动态查询
//        return sysRoleRepository.findAll(pageRequest);
        Page<SysRole> all = sysRoleRepository.findAll(pageRequest);
        List<SysRoleDTO> dtos = SysRoleConverter.conver(all.getContent());
        return new PageImpl<>(dtos, pageRequest, all.getTotalElements());
    }

    @Override
    public List<SysRole> findAll() {
        return sysRoleRepository.findAll();
    }

    @Override
    public SysRoleDTO findById(Long roleId) {
        return SysRoleConverter.conver(sysRoleRepository.findById(roleId).get());
    }

    @Override
    @Transactional
    public SysRole saveOrUpdateSysRole(SysRoleDTO roleDTO) {
        SysRole sysRole = sysRoleRepository.save(SysRoleConverter.conver(roleDTO));
        //保存角色与菜单关系
        sysRoleMenuService.saveOrUpdate(sysRole.getRoleId(), roleDTO.getMenuIdList());

        return sysRole;
    }

    @Override
    @Transactional
    public void deleteBatch(Long[] roleIds) {
        //删除角色
        sysRoleRepository.deleteByRoleId(roleIds);
        //删除角色与菜单关联
        sysRoleMenuService.deleteBatchByRoleId(roleIds);
        //删除角色与用户关联
        sysUserRoleService.deleteBatch(roleIds);
    }
}
